package lcof;

import pojo.TreeNode;

/**
 * @BelongsProject: LeetCode
 * @BelongsPackage: lcof
 * @Author: 江岸
 * @CreateTime: 2021-06-05 18:25
 * @Description: 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
 */
public class LowestCommonAncestor68I {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        while (root!=null){
            if (root.val<p.val && root.val<q.val){
                //如果根节点小于p和q，说明pq都在根节点右子树上
                root = root.right;
            }else if (root.val>p.val && root.val>q.val){
                //如果根节点大于p和q，说明pq都在根节点左子树上
                root = root.left;
            }else {
                break;
            }
        }
        return root;
    }
}
